<template>
  <div class="register-container">
    <el-form ref="registerForm" :model="registerForm" :rules="rules" @submit.native.prevent="handleRegister">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" autocomplete="username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="registerForm.password" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="registerForm.confirmPassword" autocomplete="new-password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister">注册</el-button>
      </el-form-item>
      <el-form-item>
        <div class="login-link">
          已有账号？<el-button type="text" @click="handleGoToLogin">登录</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 15, message: '用户名长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value === '') {
              callback(new Error('请再次输入密码'));
            } else if (value !== this.registerForm.password) {
              callback(new Error('两次输入的密码不匹配'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          // 注册逻辑
          console.log('注册信息', this.registerForm);
          // 通常会在这里发送请求到后端进行注册
          this.$message.success('注册成功');
          // 注册成功后可以跳转到登录页或其他页面
        } else {
          console.log('输入有误！');
          return false;
        }
      });
    },
    handleGoToLogin() {
      // 跳转到登录页面的逻辑
      this.$router.push('/login');
    }
  }
};
</script>

<style scoped>
.register-container {
  width: 300px;
  margin: 50px auto;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
}

.login-link {
  text-align: center;
}
</style>
